package com.example.service.impl;

import com.example.mapper.CategoryMapper;
import com.example.pojo.Category;
import com.example.service.CategoryService;
import com.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    //新增文章分类
    @Override
    public void add(Category category){
        // 自动填补最小空缺ID
        Integer gapId = categoryMapper.findFirstGapId();
        if (gapId == null) {
            gapId = Optional.ofNullable(categoryMapper.findMaxId()).orElse(0) + 1;
        }
        category.setId(gapId);
        //补充属性值
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        category.setCreateUser(userId);
        categoryMapper.add(category);
    }

    //查询分类列表
    @Override
    public List<Category> list() {
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer)map.get("id");
        return  categoryMapper.list(userId);
    }
    //查看分类详情
    @Override
    public Category findById(Integer id) {
        Category c = categoryMapper.findById(id);
        return c;
    }

    //更新文章分类
    @Override
    public void update(Category category){
        category.setUpdateTime(LocalDateTime.now());
        categoryMapper.update(category);
    }

    //删除文章分类
    @Override
    public void delete(Integer id) {
        //获取当前用户ID（确保只能删除自己的分类）
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        //可选：先查询分类是否存在（避免无效操作）
        Category category = categoryMapper.findById(id);
        if (category == null) {
            throw new RuntimeException("分类不存在或已被删除");
        }
        //校验权限（确保用户只能删除自己的分类）
        if (!userId.equals(category.getCreateUser())) {
            throw new RuntimeException("无权删除他人分类");
        }
        // 4. 执行删除
        categoryMapper.delete(id);
    }
}
